import {Button, Empty, Input, List, message, Modal, Radio, Typography} from "antd";
import React from "react";
import {Component} from "react";
import {GET_EXAM_PAPER, SUBMIT_EXAM_RECORD} from "../../api/APIURLDefine";
import {AxioInstance} from "../../api/AxiosHelper";
import "./index.css";
import AuthenticateModal from "../../components/authenticateModal";
import {inject, observer} from "mobx-react";
import SubmitModal from "../../components/submitModal";
import {newGuid, ParseDate} from "../../utils/Utils";
import MdShow from "../../components/MdShow";

const {Title} = Typography;

interface ExamPageState {
    zones: Array<any>;
    answers: { [key: number]: string };
    title: string;
    visible: boolean;
    startTime: string;
    endTime: string;
    examId: number;
    examResults: Array<any>;
}

const qType = {
    1: "选择题",
    2: "判断题",
    3: "填空题",
    4: "简答题",
};

@inject("globalStore")
@observer
class ExamPage extends Component<any, ExamPageState> {
    constructor(props: any) {
        super(props);
        this.state = {
            zones: [],
            answers: {},
            title: "",
            visible: false,
            startTime: "",
            endTime: "",
            examId: -1,
            examResults: [],
        };
    }

    componentDidMount() {
        var params = new URLSearchParams(this.props.history.location.search);
        var id = 1;
        if (params.has("id")) {
            id = parseInt(params.get("id"));
        }
        AxioInstance.get(`${GET_EXAM_PAPER}?id=${id}`).then((data: any) => {
            this.setState({examId: id, startTime: ParseDate(new Date())});
            this.setState({zones: data.zones});
        });
    }

    onCancel() {
        this.setState({visible: false});
    }

    private onAnswerChange(id: number, answer: string) {
        const temp = {...this.state.answers};
        temp[id] = answer;
        console.log(temp);
        this.setState({answers: temp});
    }

    private onRenderQuestion(item: any, index: number) {
        const radioStyle = {
            display: "block",
            height: "30px",
            lineHeight: "30px",
            marginLeft: "0.25rem",
            Color: "#333333",
            fontSize: "0.22rem",
            marginTop: "0.23rem",
        };

        switch (item.type) {
            case 1:
                return (
                    <div
                        style={{
                            minHeight: "2rem",
                        }}
                    >
                        <div style={{marginBottom: "0.45rem"}}>
                            <div
                                style={{
                                    color: "#333333",
                                    fontSize: "0.22rem",
                                    display: "flex"
                                }}
                            >
                                <span>{`${index + 1}.`}</span> <MdShow id={newGuid()}
                                                                       style={{width: "98%"}}
                                                                       value={item.content}/>
                            </div>
                            {/* <Radio.Group > */}

                            {item.selections.map((selection, index) => {
                                return (
                                    <Radio
                                        key={item.id + index}
                                        onClick={(e: any) => {
                                            var v = index + "";
                                            console.log(v)
                                            if (!this.state.answers[item.id]) {
                                                //选中
                                                this.onAnswerChange(item.id, v);
                                            } else if (
                                                this.state.answers[item.id] &&
                                                this.state.answers[item.id].indexOf(v) < 0
                                            ) {
                                                //选中
                                                this.onAnswerChange(
                                                    item.id,
                                                    this.state.answers[item.id] + "," + v
                                                );
                                            } else {
                                                if (this.state.answers[item.id]) {
                                                    if (
                                                        this.state.answers[item.id].indexOf(
                                                            index + ""
                                                        ) == 0
                                                    ) {
                                                        //当只选中了一个选项时
                                                        if (this.state.answers[item.id].length == 1) {
                                                            this.onAnswerChange(item.id, null);
                                                        } else {
                                                            //当多选时 去掉开头
                                                            this.onAnswerChange(
                                                                item.id,
                                                                this.state.answers[item.id].replace(v + ",", "")
                                                            );
                                                        }
                                                    } else {
                                                        this.onAnswerChange(
                                                            item.id,
                                                            this.state.answers[item.id].replace("," + v, "")
                                                        );
                                                    }
                                                }
                                            }
                                        }}
                                        checked={
                                            this.state.answers[item.id] &&
                                            this.state.answers[item.id].indexOf(index + "") >= 0
                                        }
                                        style={radioStyle}
                                        value={index}
                                    >
                                        <span>{String.fromCharCode(65 + index) + '. '}</span> <MdShow id={newGuid()}
                                                                                                      style={{
                                                                                                          width: "98%",
                                                                                                          display: "inline-flex"
                                                                                                      }}
                                                                                                      value={selection}/>
                                    </Radio>
                                );
                            })}
                        </div>
                        {/* </Radio.Group> */}
                    </div>
                );
            case 2:
                return (
                    <div
                        style={{
                            minHeight: "2rem",
                        }}
                    >
                        <div
                            style={{
                                color: "#333333",
                                fontSize: "0.22rem",
                                display: "flex"
                            }}
                        >
                            <span>{`${index + 1}.`}</span> <MdShow id={newGuid()}
                                                                   style={{width: "98%"}}
                                                                   value={item.content}/>
                        </div>
                        <Radio.Group
                            onChange={(e) => {
                                this.onAnswerChange(item.id, e.target.value);
                            }}
                        >
                            <Radio style={radioStyle} value={1}>
                                {`A、${"正确"}`}
                            </Radio>
                            <Radio style={radioStyle} value={0}>
                                {`B、${"错误"}`}
                            </Radio>
                        </Radio.Group>
                    </div>
                );
            case 3:
                return (
                    <div
                        style={{
                            minHeight: "2rem",
                            display: "flex",
                            flexDirection: "column",
                            marginBottom: "0.45rem",
                        }}
                    >
                        <div
                            style={{
                                color: "#333333",
                                fontSize: "0.22rem",
                                display: "flex"
                            }}
                        ><span>{`${index + 1}.`}</span> <MdShow id={newGuid()}
                                                                style={{width: "98%"}}
                                                                value={item.content}/></div>
                        <Input.TextArea
                            onChange={(e) => this.onAnswerChange(item.id, e.target.value)}
                            style={{height: "1.95rem", marginTop: "0.29rem"}}
                        />
                    </div>
                );
            case 4:
                return (
                    <div
                        style={{
                            minHeight: "2rem",
                            display: "flex",
                            flexDirection: "column",
                            padding: "0.1rem",
                            marginBottom: "0.45rem",
                        }}
                    >
                        <div
                            style={{
                                color: "#333333",
                                fontSize: "0.22rem",
                                display: "flex"
                            }}
                        ><span>{`${index + 1}.`}</span> <MdShow id={newGuid()}
                                                                style={{width: "98%"}}
                                                                value={item.content}/></div>
                        <Input.TextArea
                            onChange={(e) => this.onAnswerChange(item.id, e.target.value)}
                            style={{height: "1.95rem", marginTop: "0.29rem"}}
                        />
                    </div>
                );
                break;
        }
    }

    private onSubmitExam() {
        var sum = this.state.zones.reduce(
            (pre, next) => pre + next.questions.length,
            0
        );
        let temp = Object.getOwnPropertyNames(this.state.answers);
        let isAllComplete = true;
        temp.forEach((element => {
            if (this.state.answers[element] === null) {
                isAllComplete = false;
            }
        }))
        if (!isAllComplete || sum > Object.keys(this.state.answers).length) {
            this.setState({
                title: "您还未答完题目，是否要提交答案？",
                visible: true,
            });
            /*  Modal.confirm({
                        title: `您还有未完成的题目${sum - Object.keys(this.state.answers).length}个，是否确认要提交答案?`,
                        okText: "确认并提交",
                        cancelText: "取消"
                    });*/
        } else {
            /*   Modal.confirm({title: `您已经完成所有的题目，是否确认要提交答案?`, okText: "确认并提交", cancelText: "取消"});*/
            this.setState({
                title: "您已答完所有题目，是否要提交答案？",
                visible: true,
            });
        }
        //
    }

    onConfirm = () => {
        this.props.globalStore.updateShowAuthModalVisible(false);
        console.log(this.state.answers)
        var results = Object.getOwnPropertyNames(this.state.answers).map((item) => {
            return {questionId: item, answer: this.state.answers[item]};
        });
        console.log(new Date().toLocaleTimeString())
        AxioInstance.post(
            SUBMIT_EXAM_RECORD,
            JSON.stringify({
                startTime: this.state.startTime,
                endTime: ParseDate(new Date()),
                examId: this.state.examId,
                examResults: results,
            })
        ).then((data) => {
            Modal.success({title: "考试结果已经提交", okText: "关闭页面", onOk: () => window.close()})
        }).catch((data) => {
            Modal.error({title: data.msg, okText: "关闭页面", onOk: () => window.close()})
        });
    };

    render() {
        var sum = this.state.zones.reduce(
            (pre, next) => pre + next.questions.length,
            0
        );
        return (
            <div className="exam-page-back">
                <div className="exam-page-container" style={{textAlign: "left"}}>
                    <div className="exam-page-header">
                        <div/>
                    </div>
                    <div className="exam-page-body">
                        {this.state.zones.length > 0 ? (
                            this.state.zones.map((item, index) => {
                                if (item.questions.length > 0) {
                                    return (<div key={index}>
                                        <div className="exam-topic-title">
                                            <div
                                                style={{
                                                    marginBottom: "0.27rem",
                                                    fontSize: "0.22rem",
                                                    fontWeight: "bold",
                                                }}
                                            >
                                                {qType[item.type]}
                                            </div>
                                        </div>
                                        <List
                                            style={{marginTop: "0.3rem"}}
                                            dataSource={item.questions}
                                            renderItem={this.onRenderQuestion.bind(this)}
                                        />
                                    </div>)
                                } else {
                                    return (<div key={index}></div>)
                                }
                            })
                        ) : (
                            <Empty/>
                        )}
                    </div>
                    {sum > 0 ? (
                        <button className="exam-btn" onClick={this.onSubmitExam.bind(this)}>
                            提交答案
                        </button>
                    ) : null}
                </div>
                <SubmitModal
                    visible={this.state.visible}
                    cancel={this.onCancel.bind(this)}
                    confirm={this.onConfirm.bind(this)}
                    title={this.state.title}
                />
            </div>
        );
    }
}

export default ExamPage;
